const fs = require('fs');
const path = require('path');
const { koaBody } = require('koa-body');

// 确保上传目录存在
const uploadDir = path.join(__dirname, '../../uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

/**
 * 文件上传中间件
 */
const upload = koaBody({
  multipart: true,
  formidable: {
    uploadDir,
    keepExtensions: true,
    maxFileSize: 10 * 1024 * 1024, // 10MB
    onFileBegin: (name, file) => {
      // 生成唯一的文件名
      const ext = path.extname(file.originalFilename);
      const fileName = `${Date.now()}-${Math.random().toString(36).substr(2)}${ext}`;
      file.filepath = path.join(uploadDir, fileName);
    }
  }
});

module.exports = upload; 